package com.sctvcloud.linshui.ui.activities;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureExternalPreviewActivity;
import com.luck.picture.lib.tools.DebugUtil;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.linshui.R;
import com.sctvcloud.linshui.application.Cache;
import com.sctvcloud.linshui.application.Constances;
import com.sctvcloud.linshui.base.BaseActivity;
import com.sctvcloud.linshui.beans.FUsers;
import com.sctvcloud.linshui.im.ImInterface;
import com.sctvcloud.linshui.ui.adapter.FindFellowVillagersChatRoomAdapter;
import com.sctvcloud.linshui.ui.adapter.holder.FindFellVillagersChatRoomHolder;
import com.sctvcloud.linshui.ui.utils.TitleUtils;
import com.sctvcloud.linshui.ui.utils.UIUtils;
import com.sctvcloud.linshui.utils.UserManager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.im.android.api.callback.RequestCallback;
import cn.jpush.im.android.api.model.ChatRoomInfo;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;

/**
 * 找老乡 ---聊天室列表
 */
public class FindFellowVillagersActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, FindFellVillagersChatRoomHolder.OnChatRommClickListener {
    @BindView(R.id.list_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerViewList;

    private FindFellowVillagersChatRoomAdapter chatRoomAdapter;
    private int index = 0;
    private int pageSize = 10;
    private List<ChatRoomInfo> chatRoomList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        imRegister();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_find_fellow_villagers);
        ButterKnife.bind(this);
    }

    @Override
    public void onLoadMore() {
        index++;
        getChatRoomData();
    }

    @Override
    public void onRefresh() {
        index = 0;
        chatRoomList.clear();
        getChatRoomData();
    }

    private void initView() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        recyclerViewList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerViewList.setItemAnimator(new DefaultItemAnimator());
    }

    private void getChatRoomData() {
        ImInterface.getInstance().getChatRoomList(index, pageSize, new RequestCallback<List<ChatRoomInfo>>() {
            @Override
            public void gotResult(int responseCode, String responseMessage, List<ChatRoomInfo> chatRoomInfos) {
                if (ListUtils.isListValued(chatRoomInfos)) {
                    chatRoomList.addAll(chatRoomInfos);
                } else {
                    refreshLayout.setLoadMoreEnabled(false);
                }
                initData();
                refreshLayout.refreshComplete();
                refreshLayout.loadMoreComplete();
            }
        });
    }
    /**
     * 极光IM注册
     *
     */
    private void imRegister() {
        if (UserManager.getInstance().isLogin()) {
            //TODO 查询用户积分数据
            final FUsers fUsers = UserManager.getInstance().getUser();
            String avatar = "";
            if (TextUtils.isEmpty(fUsers.getAvatar())) {
                avatar = UrlUtils.linkUrls(Constances.ST_BASE_URL, fUsers.getAvatar());
            }
            ImInterface.getInstance().imUserRegister(fUsers.getPhoneNumber(), "123456", fUsers.getNickName(), avatar, new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    if (s.equalsIgnoreCase("Success"))
                        JLog.d("---极光 IM 注册成功--");
                    imLogin(fUsers);
                }
            });
        }
    }

    /**
     * 极光IM登陆
     *
     * @param fUsers
     */
    private void imLogin(final FUsers fUsers) {
        ImInterface.getInstance().imUserLogin(fUsers.getPhoneNumber(), "123456", new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                JLog.d("---极光 IM 登录成功--");
                refreshLayout.autoRefresh();
                getIMUserInfo();
            }
        });

    }

    /**
     * 初始化当前IM的登录用户信息
     */
    private void getIMUserInfo() {
        UserInfo info = ImInterface.getInstance().getMyUserInfo();
        if(null!=info) {
            Cache.getInstance().setImUserInfo(info);
            FUsers fUsers = UserManager.getInstance().getUser();
            if (TextUtils.isEmpty(info.getAvatar()) && null != fUsers && !TextUtils.isEmpty(fUsers.getAvatar())) {
                //当当前IM用户的头像为空，cms用户有头像时，初始化IM头像
                downloadAvatar(UrlUtils.linkUrls(Constances.ST_BASE_URL, fUsers.getAvatar()));
            }
        }
    }

    private void initData() {
        if (null == chatRoomAdapter) {
            chatRoomAdapter = new FindFellowVillagersChatRoomAdapter(this, chatRoomList, this);
            recyclerViewList.setAdapter(chatRoomAdapter);
        } else {
            chatRoomAdapter.setData(chatRoomList);
        }

    }

    @Override
    public void OnChatRoomClick(ChatRoomInfo roomInfo) {
        Intent intent = new Intent(this, ChatRoomActivity.class);
        intent.putExtra(ChatRoomActivity.CHAT_ROOM_ID, roomInfo.getRoomID());
        intent.putExtra(ChatRoomActivity.CHAT_ROOM_TITLE, roomInfo.getName());
        startActivity(intent);
    }

    @OnClick({R.id.title_top_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_back:
                finish();
                break;
        }
    }

    /**
     * 将网络头像下载到本地，然后上传到IM账户下。
     * @param picUrl
     */
    private void downloadAvatar(final String picUrl) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                showLoadingImage(picUrl);
            }
        }).start();

    }

    // 下载图片保存至手机
    public void showLoadingImage(String urlPath) {
        try {
            URL u = new URL(urlPath);
            String path = PictureFileUtils.createDir(this,
                    System.currentTimeMillis() + ".png", PictureFileUtils.CAMERA_PIC_PATH);
            byte[] buffer = new byte[1024 * 8];
            int read;
            int ava = 0;
            long start = System.currentTimeMillis();
            BufferedInputStream bin;
            bin = new BufferedInputStream(u.openStream());
            BufferedOutputStream bout = new BufferedOutputStream(
                    new FileOutputStream(path));
            while ((read = bin.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
                ava += read;
                long speed = ava / (System.currentTimeMillis() - start);
                DebugUtil.i("Download: " + ava + " byte(s)"
                        + "    avg speed: " + speed + "  (kb/s)");
            }
            bout.flush();
            bout.close();
            Message message = handler.obtainMessage();
            message.what = 200;
            message.obj = path;
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 200:
                    String path = (String) msg.obj;
                    updateIMUserAvatar(path);
                    break;
            }
        }
    };

    /**
     * 更新 IM用户头像
     *
     * @param path
     */
    private void updateIMUserAvatar(String path) {
        try {
            File icon = new File(path);
            if (null != icon) {
                ImInterface.getInstance().imUpdateUserAvatar(icon, new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        JLog.d("---updateIMUserAvatar -imUpdateUserAvatar--s = " + s);
                    }
                });
            } else {
                JLog.d("---updateIMUserAvatar -imUpdateUserAvatar--iconFile = null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
